package com.fish.yssb.api;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.util.Log;

import com.fish.yssb.Consts;
import com.fish.yssb.R;
import com.fish.yssb.db.bean.BaseInfoTable;
import com.fish.yssb.ui.page.activity.his.hisDetailYCActivity;
import com.fish.yssb.ui.page.util.LogUtil;
import com.hy.srv101.CmdDataCell;
import com.hy.srv101.CmdFileAct;
import com.hy.srv101.CmdGen;
import com.hy.srv101.CmdLib;
import com.hy.srv101.CmdRWSetting;
import com.hy.srv101.CmdSynTime;
import com.hy.srv101.CmdUpgrade;
import com.hy.srv101.I4YData;
import com.hy.srv101.ICmdFace;
import com.hy.srv101.MemLib;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import static com.fish.yssb.Consts.isRealSQ;


public class setApi
{
	private static boolean thread_status;
	private static int cmdtype = 0;
	private static ICmdFace cmdFace;
	private static setApi m_setApi;
	private static Context m_context;

	private static long thread_stime = 0l;
	private static int timeout_max = 15;
	private static boolean run_flag = false;
	private static CmdRWSetting  cmdRd;
	public static setApi getInstance(Context context)
	{
		if(!run_flag) {
			m_context = context;
		}
		if(m_setApi == null)
		{
			thread_status = true;
			m_setApi =new setApi();

		}
		return m_setApi;
	}

	private static class CustomThread implements Runnable{
		@Override
		public void run() {
			// 处理耗时逻辑
			while(run_flag) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					System.out.println(e.getMessage());
				}
				long currentTimeMillis = System.currentTimeMillis();
				if ((currentTimeMillis - thread_stime) / 1000 > timeout_max) {
					run_flag = false;

					retData tmp = new retData();
					tmp.setRet(Consts.cm_timeout);
					tmp.setType(cmdtype);
					EventBus.getDefault().post(tmp);
					thread_status = true;
					break;
				}

				if(cmdFace.cmdRunEnd() || !isRealSQ)
				{
					thread_status = true;
					if(cmdtype!=Consts.cm_r_real_para) {

						System.out.println("-------------------------cmdRunEnd------------------------------------------" + cmdFace.cmdRunEnd());


						retData tmp = new retData();
						tmp.setRet(Consts.cm_end);
						tmp.setType(cmdtype);
						tmp.setStatus(cmdFace.cmdRunResult()?1:0);
						if (cmdtype == Consts.cm_r_const_para) {
						if(!isRealSQ)
						{
							ArrayList<CmdDataCell> list = new ArrayList<>();
							CmdDataCell cell =  CmdDataCell.newInstance_ParaWrite(45,(short)388,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(45,(short)1924,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)2180,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)2436,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)2692,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)2948,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)3204,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)3460,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)3716,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)3972,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)4228,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)4484,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)4740,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)4996,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)5252,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)5508,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)5764,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)6020,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)6276,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)6532,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)6788,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)7044,1);
							list.add(cell);
							cell =  CmdDataCell.newInstance_ParaWrite(32,(short)7300,1);
							list.add(cell);
							tmp.list = list;
						}else {

								ArrayList<CmdDataCell> list = cmdRd.lstDatas;
								tmp.list = list;
						}
						}
						EventBus.getDefault().post(tmp);
					}
					else{


						retData tmp = new retData();
						tmp.setRet(Consts.cm_end);
						tmp.setType(cmdtype);
						tmp.setStatus(cmdFace.cmdRunResult()?1:0);
						if (cmdtype == Consts.cm_r_real_para) {
							Collection<I4YData> listyc = MemLib.GetYCDatas();
							Collection<I4YData> listym = MemLib.GetYMDatas();
							Collection<I4YData> listyx = MemLib.GetYXDatas();
							tmp.list_yc = listyc;
							tmp.list_ym = listym;
							tmp.list_yx = listyx;
						}
						EventBus.getDefault().post(tmp);
						try {
							Thread.sleep(5000);
						} catch (InterruptedException e) {
							System.out.println(e.getMessage());
						}
					}

					break;
				}
			}


		}
	}

	//1 遥信 2.遥脉，3遥测
	public static Collection<I4YData> getRealData(int type)
	{

		if(type==1)
		{
			return MemLib.GetYXDatas();
		}else if(type==2){
			return MemLib.GetYMDatas();
		}else if(type==3){
			return MemLib.GetYCDatas();
		}else{
			return MemLib.GetYXDatas();
		}

	}



	//软件升级
	public static int updateVer(String verfile)
	{
		//CmdLib.pollCmd();
		LogUtil.addLog("命令执行","执行版本更新");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_updatever;
			//CmdLib.pollCmd();
			cmdFace = CmdUpgrade.newInstance_Start("Sr1250Ftu_Arm.out");

			CmdLib.addCmd(cmdFace);
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}

	//时间同步
	public static int sysTime(Date date)
	{
		//CmdLib.pollCmd();
		LogUtil.addLog("命令执行","执行时间同步");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_systime;
			//CmdLib.pollCmd();
			cmdFace = CmdSynTime.newInstance(date);
			CmdLib.addCmd(cmdFace);
			System.out.println("--------------------------------systime");

			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}

	private static short StringToInt(String str)
	{
		if(str.length() ==6) {

			String tmp = str.substring(4,6)+str.substring(2,4);
			Log.e("=========tmp:",tmp);
			short num = Short.parseShort(tmp,16);
			return num;
		}
		return 0;
	}

	//设备信息读取
		public static int setConstPara(ArrayList<BaseInfoTable> list)
	{
		//CmdLib.pollCmd();
		LogUtil.addLog("命令执行","设置基本参数");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_w_const_para;
			//CmdLib.pollCmd();
			CmdRWSetting  cmdWr = CmdRWSetting.newInstance_Write();

			for(int i=0;i<list.size();i++) {

				short num = StringToInt(list.get(i).getConnAdr());

				CmdDataCell dat257 = CmdDataCell.newInstance_ParaWrite(CmdDataCell.PARA_DATA_TAG_STRING, (short) (num), 4);

				// private int  dataType; // 0.无 1.布尔 2.浮点 3.整形
				if(list.get(i).getDataType() == 0 || list.get(i).getDataType() == 1 || list.get(i).getDataType() == 3)
				{
					int val = Integer.parseInt(list.get(i).getRealVal());
					dat257.SetValue(val);
				}else if(list.get(i).getDataType() == 2)
				{
					Float val = Float.parseFloat(list.get(i).getRealVal());
					dat257.SetValue(val);
				}else


				cmdWr.lstDatas.add(dat257);
			}
			cmdFace = cmdWr;
			CmdLib.addCmd(cmdFace);
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}


	//设备信息读取
	public static int writesq()
	{
		//CmdLib.pollCmd();
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {

			cmdtype = Consts.cm_writesq;
			//CmdLib.pollCmd();
			//???????????
			//设备读取api，目前提供的api中没找到？
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}

	//定值参数读取
	public static int r_const_para()
	{
		//CmdLib.pollCmd();
		LogUtil.addLog("命令执行","实时数据查询");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_r_const_para;
			//CmdLib.pollCmd();
			//读取多个定值参数，命令执行之后，通过什么方法或是那个参数获取读的值？

			cmdRd = CmdRWSetting.newInstance_Read(true);
			/*
			CmdDataCell dat33793 = CmdDataCell.newInstance_ParaRead((short)(33793));
			CmdDataCell dat33796 = CmdDataCell.newInstance_ParaRead((short)(33796));
			CmdDataCell dat33845 = CmdDataCell.newInstance_ParaRead((short)(33845));
			cmdRd.lstDatas.add(dat33793);
			cmdRd.lstDatas.add(dat33796);
			cmdRd.lstDatas.add(dat33845);*/
			cmdFace = cmdRd;
			CmdLib.addCmd(cmdFace);
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}

	//实时数据查询
	public static int r_real_para()
	{
		//CmdLib.pollCmd();
		LogUtil.addLog("命令执行","实时数据查询");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_r_real_para;
			CmdGen cmdGen = CmdGen.GI_NewInstance();

			cmdFace =cmdGen;
			CmdLib.addCmd(cmdGen);

			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}

	private static char commit ;
	//历史数据列表
	public static int tv_his_list(int type)
	{
		//CmdLib.pollCmd();
		LogUtil.addLog("命令执行","历史记录查询");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_his_list;
//			char commit = CmdFileAct.SOE_FILE;
			switch (type)
			{
				case 1:  //SOE事件记录
					commit = CmdFileAct.SOE_FILE;
				break;
				case 2:  //遥控操作记录
					break;
				case 3:  //极值数据
					break;
				case 4:  //定点记录数据
					break;
				case 5:  //日冻结电能量
					break;
				case 6:  //功率反向电能量冻结值
					break;
				case 7: //日志
					break;
				case 8: //录波
					break;
			}


			CmdFileAct cmdRd =CmdFileAct.FileDir_NewInstance(commit); // 读取soe文件？
			cmdFace = cmdRd;
			CmdLib.addCmd(cmdFace);
//			CmdFileAct  cmdRd =CmdFileAct.WavDir_NewInstance(？？); //读取录播文件？，这里参数传什么？
//			cmdFace = cmdRd;
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}


	public static ArrayList<CmdFileAct.HisFileInfo> getFiles()
	{
	  return 	CmdFileAct.FileDir_NewInstance(commit).lstHisFile;
	}

	public static String getFilesName()
	{
		String str="";
		//获取文件地址
		return str;
	}


	//历史文件下载
	public static int tv_his_filedown()
	{
		//CmdLib.pollCmd();
		LogUtil.addLog("命令执行","实时数据下载");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_his_filedown;
			//CmdLib.pollCmd();
			cmdFace = cmdRd;
			CmdLib.addCmd(cmdFace);
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}


	//预制
	public static int tv_w_sub_ctrl(short num ,boolean flag)
	{

		LogUtil.addLog("命令执行","预制操作");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_w_ctrl;

			{//预置
				cmdFace = CmdGen.Preset01_NewInstance(num, false, flag);//预制
				CmdLib.addCmd(cmdFace);
			}



//			start_thread();
			//???????????
			//展示时候需要知道当前是开还是合？目前提供的api中没找到？?
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}

	//执行
	public static int tv_w_sub_ctrl_1(short num ,boolean flag)
	{
		LogUtil.addLog("命令执行","执行操作");
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_w_ctrl_2;

			{//执行
				cmdFace = CmdGen.Set01_NewInstance(num, false, flag);//执行
				CmdLib.addCmd(cmdFace);
			}

			//展示时候需要知道之前是否有过预制或是执行？目前提供的api中没找到？?
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}


	//发预制/执行命令
	public static int tv_w_ctrl()
	{
		//CmdLib.pollCmd();
		if(!thread_status)
		{
			return -1;
		}
		thread_status = false;
		try {
			cmdtype = Consts.cm_w_ctrl_2;
			//CmdLib.pollCmd();
			//???????????
			//1.第2个参数填什么？
			//2.预制、执行命令发送失败之后，是不是30内不能再执行，必须等时间到才能再次执行
//			Preset01_NewInstance(0x00,);//预制
//			Set01_NewInstance();//执行
			start_thread();

		}catch (Exception ex)
		{
			thread_status = true;
			ex.printStackTrace();
			getStackTraceInfo(ex);
			return -2;
		}
		return 1;

	}



	private static void start_thread()
	{
		retData tmp = new retData();
		tmp.setRet(Consts.cm_start);
		tmp.setType(cmdtype);
		EventBus.getDefault().post(tmp);
		thread_stime = System.currentTimeMillis();
		run_flag = true;
		new Thread(new CustomThread()).start();
	}

	private static void getStackTraceInfo(Exception e) {

		StringWriter sw = null;
		PrintWriter pw = null;

		try {
			sw = new StringWriter();
			pw = new PrintWriter(sw);
			e.printStackTrace(pw);//将出错的栈信息输出到printWriter中
			pw.flush();
			sw.flush();
			ClipboardManager cm;
			ClipData mClipData;
//获取剪贴板管理器：
			cm = (ClipboardManager) m_context.getSystemService(Context.CLIPBOARD_SERVICE);
			mClipData = ClipData.newPlainText("Label", sw.toString());
			cm.setPrimaryClip(mClipData);

//			return sw.toString();
		} catch (Exception ex) {

			return;
		} finally {
			if (sw != null) {
				try {
					sw.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (pw != null) {
				pw.close();
			}
		}

	}
}
